By
yusijia
Updated:
题意
给定一序列的单词按照字典序输入,要求某些单词是由这其中的其它两个单词拼接而成的单词按照字典序输出
分析:
把输入的单词建一棵字典树,然后每单单词拆成两半去字典树里找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include <cstdio> #include <iostream> #include <cstdlib> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 50010; const int N = 150; const int M = 26;
struct Node{ int mark; Node *childs[M]; };
Node node[MAXN * N]; Node *root; int pos, numWord; char word[MAXN][N];
Node *newnode(){ node[pos].mark = 0; for(int i = 0; i < M; i++){ node[pos].childs[i] = NULL; } return &node[pos++]; }
void Insert(char *str) { int len = strlen(str); Node *s = root; for(int i = 0; i < len; i++){ int index = str[i] - 'a'; if(s->childs[index] == NULL) s->childs[index] = newnode(); s = s->childs[index]; } s->mark = 1; }
bool Search(char *str) { Node *s = root; int len = strlen(str); for(int i = 0; i < len; i++){ int index = str[i] - 'a'; if(s->childs[index] == NULL) return false; s = s->childs[index]; } return s->mark == 1; }
void solve() { for(int i = 0; i < numWord; i++){ int len = strlen(word[i]); for(int j = 1; j < len; j++){ char temp[N]; strcpy(temp, word[i]); temp[j] = '\0'; if(Search(temp) && Search(word[i] + j)){ printf("%s\n", word[i]); break; } } } }
int main() { numWord = 0; pos = 0; root = newnode(); while(scanf("%s", word[numWord]) != EOF){ Insert(word[numWord++]); } solve(); return 0; }
|